×
☰ See All Chapters

Java Default Methods

An abstract class can have both abstract and concrete methods (concrete methods are methods with complete implementation). Before java 1.8, interface can have only abstract methods, from java 1.8 interfaces can also have both concrete and abstract methods. Only the difference is that when we write the concrete methods in interface, it should be defined with new non-access specifier “default” and such methods are called as default methods. From java 1.8, “default” is a new keyword and it shouldn’t be used for identifiers. From java 1.8 we can declare static method inside interface, when we declare a static concrete method inside interface we should not make it default.

  1. We can declare any number of default, static and abstract methods inside interface. 

  2. An interface can have one or more default methods and still be functional, if has only one abstract method. 

  3. After having default and static methods inside the interface, one may think about the need of abstract class in Java. Below is the difference between interface and abstract class in java 1.8 

interface vs abstract class in java 1.8

 

Interface

Abstract class

abstract methods

We can write

We can write

Concrete methods

We can write with default non access specifier

We can write

Variables other than static final variables

We cannot write

We can write

constructor

We cannot write

We can write

Java Default Methods Example

package com.java4coding;

 

interface PrintText {

        public default void printHi () {

                System.out.println("Hi");

        }

       

        void printHello();

       

        public static void printHey () {

                System.out.println("Hey");

        }

}

 

class PrintTextImpl implements PrintText {

        @Override

        public void printHello() {

                System.out.println("Hello");

        }

}

 

 

public class Demo {

 

        public static void main(String[] args) {

                PrintTextImpl printTextImpl = new PrintTextImpl();

                printTextImpl.printHi();

                printTextImpl.printHello();

               

                PrintText.printHey();//accessing static method of interface

        }

}

 


All Chapters
Author